<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="username"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="renderTable">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in arr" :key="item.id">
          <td>{{index+1}}</td>
          <td>{{item.username}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="delTable(index)">删除</button>
            <button @click="replayTable(item)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      arr:[
      {id:1,username:'ikun',age:'18',gender:'男'},
       {id:2,username:'keke',age:'20',gender:'女'}
      ],
      id:'',
      username:'',
      age:'',
      gender:'',
    }
  },
  methods:{
    renderTable(){
      if(this.id){
      this.arr.forEach(item=>{if(item.id===this.id){item.username=this.username,item.age=this.age,item.gender=this.gender}})
      this.username=''
      this.age=''
      this.gender=''
      this.id=''
      }
      else{
    if(this.username&&this.age&&this.gender){
    const obj={
      id:this.arr.length+1,username:this.username,age:this.age,gender:this.gender,
    }
    this.arr=[...this.arr,obj]
    this.username=''
    this.age=''
    this.gender=''
      }
     else{
      alert('请填写正确内容')
     }
      }
    },
    delTable(num){
    this.arr= this.arr.filter((item,index)=>index!==num)
    },
    replayTable(item){
    this.id=item.id
    this.username=item.username
    this.age=item.age
    this.gender=item.gender
    }
  },
}
</script>
